package com.glureau.aib.client.ai;

import com.glureau.aib.shared.ai.AiInfo;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TextBox;

public class AiChangeHandler implements ChangeHandler {

	private final AiServiceAsync AiService = GWT.create(AiService.class);
	private AiInfo m_aiInfo;

	@Override
	public void onChange(ChangeEvent event) {
		Object source = event.getSource();
		if (source instanceof TextBox) {
			TextBox textBox = (TextBox) source;
			String sourceName = textBox.getName();
			if (sourceName.equals("name")) {
				m_aiInfo.setName(textBox.getText());
			}
		}
		saveAi(m_aiInfo);
	}

	private void saveAi(AiInfo result) {
		AiService.saveAi(Cookies.getCookie("sid"), result,
				new AsyncCallback<Void>() {

					@Override
					public void onSuccess(Void result) {
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Warning : the modification is not saved ! Please contact the webmaster.");
					}
				});
	}

	public void setAiInfo(AiInfo pi) {
		m_aiInfo = pi;
	}
}
